import { Context, Next } from "koa";
import { Pagination } from "../types/base";
import { DEFAULT_PAGE, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE } from "../common/constants";

// 分页信息中间件
export default () => async (ctx: Context, next: Next) => {
  // 处理分页信息
  try {
    const pagination: Pagination = {
      page: 1,
      pageSize: 10,
      sortBy: "id",
      sortOrder: "desc"
    };

    // 获取分页列表接口的方法，目前只支持GET
    const pagParams = <Pagination><unknown>ctx.query;
    pagination.page = Math.max(1, parseInt(`${pagParams.page}`, 10) || DEFAULT_PAGE);

    const pageSize = parseInt(`${pagParams.pageSize}`, 10) || DEFAULT_PAGE_SIZE;
    pagination.pageSize = Math.max(Math.min(pageSize, MAX_PAGE_SIZE), 1);
    pagination.sortBy = pagParams.sortBy || "id";
    pagination.sortOrder = pagParams.sortOrder === "asc" ? "asc" : "desc";

    ctx.reqPagination = pagination;
  } catch (e) {
    throw new Error("10005");
  }

  // 执行后续请求
  const res = await next();
  return res;
};
